// Bristleback plugin - Copyright (c) 2010 bristleback.googlecode.com
// ---------------------------------------------------------------------------
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by the
// Free Software Foundation; either version 3 of the License, or (at your
// option) any later version.
// This library is distributed in the hope that it will be useful,
// but without any warranty; without even the implied warranty of merchantability
// or fitness for a particular purpose.
// You should have received a copy of the GNU Lesser General Public License along
// with this program; if not, see <http://www.gnu.org/licenses/lgpl.html>.
// ---------------------------------------------------------------------------
package pl.bristleback.server.bristle.utils;

import org.apache.log4j.Logger;
import pl.bristleback.server.bristle.exceptions.ImplementationResolvingException;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;

/**
 * This class is a part of Stripes Framework, version 1.5, <a href="http://www.stripesframework.org">www.stripesframework.org</a>.
 * Class is modified by Wojciech Niemiec.
 * <p>ResolverUtil is used to locate classes that are available in the/a class path and meet
 * arbitrary conditions. The two most common conditions are that a class implements/extends
 * another class, or that is it annotated with a specific annotation. However, through the use
 * of the {@link Test} class it is possible to search using arbitrary conditions.</p>
 * <p/>
 * <p>A ClassLoader is used to locate all locations (directories and jar files) in the class
 * path that contain classes within certain packages, and then to load those classes and
 * check them. By default the ClassLoader returned by
 * {@code Thread.currentThread().getContextClassLoader()} is used, but this can be overridden
 * by calling {@link #setClassLoader(ClassLoader)} prior to invoking any of the {@code find()}
 * methods.</p>
 * <p/>
 * <p>General searches are initiated by calling the
 * {@link #find(pl.bristleback.server.bristle.utils.ResolverUtil.Test, String)} ()} method and supplying
 * a package name and a Test instance. This will cause the named package <b>and all sub-packages</b>
 * to be scanned for classes that meet the test. There are also utility methods for the common
 * use cases of scanning multiple packages for extensions of particular classes, or classes
 * annotated with a specific annotation.</p>
 * <p/>
 * <p>The standard usage pattern for the ResolverUtil class is as follows:</p>
 * <p/>
 * <pre>
 * ResolverUtil&lt;ActionBean&gt; resolver = new ResolverUtil&lt;ActionBean&gt;();
 * resolver.findImplementation(ActionBean.class, pkg1, pkg2);
 * resolver.find(new CustomTest(), pkg1);
 * resolver.find(new CustomTest(), pkg2);
 * Collection&lt;ActionBean&gt; beans = resolver.getClasses();
 * </pre>
 *
 * @author Tim Fennell
 */
public final class ResolverUtil<T> {
  private static Logger log = Logger.getLogger(ResolverUtil.class.getName());

  private static final int INITIAL_BUFFER_CAPACITY = 100;

  /**
   * The set of matches being accumulated.
   */
  private Set<Class<? extends T>> matches = new HashSet<Class<? extends T>>();

  /**
   * The ClassLoader to use when looking for classes. If null then the ClassLoader returned
   * by Thread.currentThread().getContextClassLoader() will be used.
   */
  private ClassLoader classLoader;

  /**
   * Provides access to the classes discovered so far. If no calls have been made to
   * any of the {@code find()} methods, this set will be empty.
   *
   * @return the set of classes that have been discovered.
   */
  public Set<Class<? extends T>> getClasses() {
    return matches;
  }

  /**
   * Returns the classloader that will be used for scanning for classes. If no explicit
   * ClassLoader has been set by the calling, the context class loader will be used.
   *
   * @return the ClassLoader that will be used to scan for classes
   */
  public ClassLoader getClassLoader() {
    if (classLoader == null) {
      return Thread.currentThread().getContextClassLoader();
    } else {
      return classLoader;
    }
  }

  /**
   * Sets an explicit ClassLoader that should be used when scanning for classes. If none
   * is set then the context classloader will be used.
   *
   * @param classLoader a ClassLoader to use when scanning for classes
   */
  public void setClassLoader(ClassLoader classLoader) {
    this.classLoader = classLoader;
  }

  /**
   * Attempts to discover classes that are assignable to the type provided. In the case
   * that an interface is provided this method will collect implementations. In the case
   * of a non-interface class, subclasses will be collected.  Accumulated classes can be
   * accessed by calling {@link #getClasses()}.
   *
   * @param parent       the class of interface to find subclasses or implementations of
   * @param packageNames one or more package names to scan (including subpackages) for classes
   * @return found implementations
   */
  public ResolverUtil<T> findImplementations(Class<?> parent, String... packageNames) {
    if (packageNames == null) {
      return this;
    }

    Test test = new IsAasignatedFrom(parent);
    for (String pkg : packageNames) {
      find(test, pkg);
    }

    return this;
  }

  public Class getImplementation(Class<?> interfaceClass, String className) {
    try {
      Test test = new IsAasignatedFrom(interfaceClass);
      Class type = getClassLoader().loadClass(className);
      if (test.matches(type)) {
        return type;
      } else {
        throw new ImplementationResolvingException(className, interfaceClass);
      }
    } catch (Exception e) {
      throw new ImplementationResolvingException(className, interfaceClass);
    }
  }

  /**
   * Scans for classes starting at the package provided and descending into subpackages.
   * Each class is offered up to the Test as it is discovered, and if the Test returns
   * true the class is retained.  Accumulated classes can be fetched by calling
   * {@link #getClasses()}.
   *
   * @param test        an instance of {@link Test} that will be used to filter classes
   * @param packageName the name of the package from which to start scanning for
   *                    classes, e.g. {@code net.sourceforge.stripes}
   * @return this object
   */
  public ResolverUtil<T> find(Test test, String packageName) {
    packageName = packageName.replace('.', '/');
    ClassLoader loader = getClassLoader();
    Enumeration<URL> urls;

    try {
      urls = loader.getResources(packageName);
    } catch (IOException ioe) {
      log.warn("Could not read package: " + packageName, ioe);
      return this;
    }

    while (urls.hasMoreElements()) {
      String urlPath = urls.nextElement().getFile();
      urlPath = StringUtil.urlDecode(urlPath);

      // If it's a file in a directory, trim the stupid file: spec
      if (urlPath.startsWith("file:")) {
        urlPath = urlPath.substring(5);
      }

      // Else it's in a JAR, grab the path to the jar
      if (urlPath.indexOf('!') > 0) {
        urlPath = urlPath.substring(0, urlPath.indexOf('!'));
      }

      log.info("Scanning for classes in [" + urlPath + "] matching criteria: " + test.toString());
      File file = new File(urlPath);
      if (file.isDirectory()) {
        loadImplementationsInDirectory(test, packageName, file);
      } else {
        loadImplementationsInJar(test, packageName, file);
      }
    }

    return this;
  }

  /**
   * Finds matches in a physical directory on a filesystem.  Examines all
   * files within a directory - if the File object is not a directory, and ends with <i>.class</i>
   * the file is loaded and tested to see if it is acceptable according to the Test.  Operates
   * recursively to find classes within a folder structure matching the package structure.
   *
   * @param test     a Test used to filter the classes that are discovered
   * @param parent   the package name up to this directory in the package hierarchy.  E.g. if
   *                 /classes is in the classpath and we wish to examine files in /classes/org/apache then
   *                 the values of <i>parent</i> would be <i>org/apache</i>
   * @param location a File object representing a directory
   */
  private void loadImplementationsInDirectory(Test test, String parent, File location) {
    File[] files = location.listFiles();
    StringBuilder builder;

    // File.listFiles() can return null when an IO error occurs!
    if (files == null) {
      log.warn("Could not list directory " + location.getAbsolutePath()
        + " when looking for classes matching: " + test);
      return;
    }

    for (File file : files) {
      builder = new StringBuilder(INITIAL_BUFFER_CAPACITY);
      builder.append(parent).append("/").append(file.getName());
      String packageOrClass;
      if (parent == null) {
        packageOrClass = file.getName();
      } else {
        packageOrClass = builder.toString();
      }

      if (file.isDirectory()) {
        loadImplementationsInDirectory(test, packageOrClass, file);
      } else if (file.getName().endsWith(".class")) {
        addIfMatching(test, packageOrClass);
      }
    }
  }

  /**
   * Finds matching classes within a jar files that contains a folder structure
   * matching the package structure.  If the File is not a JarFile or does not exist a warning
   * will be logged, but no error will be raised.
   *
   * @param test    a Test used to filter the classes that are discovered
   * @param parent  the parent package under which classes must be in order to be considered
   * @param jarfile the jar file to be examined for classes
   */
  private void loadImplementationsInJar(Test test, String parent, File jarfile) {

    try {
      JarEntry entry;
      JarInputStream jarStream = new JarInputStream(new FileInputStream(jarfile));

      while ((entry = jarStream.getNextJarEntry()) != null) {
        String name = entry.getName();
        if (!entry.isDirectory() && name.startsWith(parent) && name.endsWith(".class")) {
          addIfMatching(test, name);
        }
      }
    } catch (IOException ioe) {
      log.error("Could not search jar file '" + jarfile + "' for classes matching criteria: "
        + test + "due to an IOException: " + ioe.getMessage());
    }
  }

  /**
   * Add the class designated by the fully qualified class name provided to the set of
   * resolved classes if and only if it is approved by the Test supplied.
   *
   * @param test the test used to determine if the class matches
   * @param fqn  the fully qualified name of a class
   */
  @SuppressWarnings("unchecked")
  protected void addIfMatching(Test test, String fqn) {
    try {
      String externalName = fqn.substring(0, fqn.indexOf('.')).replace('/', '.');
      ClassLoader loader = getClassLoader();
      log.trace("Checking to see if class " + externalName + " matches criteria [" + test + "]");

      Class type = loader.loadClass(externalName);
      if (test.matches(type)) {
        matches.add((Class<T>) type);
      }
    } catch (Exception e) {
      log.warn("Could not examine class '" + fqn + "' due to a "
        + e.getClass().getName() + " with message: " + e.getMessage());
    }
  }


  /**
   * A simple interface that specifies how to test classes to determine if they
   * are to be included in the results produced by the ResolverUtil.
   */
  public static interface Test {
    /**
     * Will be called repeatedly with candidate classes. Must return True if a class
     * is to be included in the results, false otherwise.
     *
     * @param type class type
     * @return true if class meets conditions
     */
    boolean matches(Class<?> type);
  }

  /**
   * A Test that checks to see if each class is assignable to the provided class. Note
   * that this test will match the parent type itself if it is presented for matching.
   */
  public static class IsAasignatedFrom implements Test {
    private Class<?> parent;

    /**
     * Constructs an IsA test using the supplied Class as the parent class/interface.
     *
     * @param parentType parent type
     */
    public IsAasignatedFrom(Class<?> parentType) {
      this.parent = parentType;
    }

    /**
     * Returns true if type is assignable to the parent type supplied in the constructor.
     */
    @SuppressWarnings("unchecked")
    public boolean matches(Class type) {
      return type != null && parent.isAssignableFrom(type);
    }

    @Override
    public String toString() {
      return "is assignable to " + parent.getSimpleName();
    }
  }
}
